<template>
  <div>
    <!-- 商品列表 -->
    <MyTable :list="list">
      <!-- 表格标题区域head 具名插槽 -->
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!-- 表格主体区域boby 具名插槽 -->
      <template #boby="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            type="text"
            class="tag-input form-control"
            style="width: 100px"
            v-if="row.inputVisible"
            v-fff
            v-model="row.inputValue"
            @blur="row.inputVisible = false"
            @keydown.esc="row.inputValue = ''"
            @keydown.enter="enterFn(row)"
          />
          <button
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            v-else
            @click="row.inputVisible = true"
          >
            +Tag
          </button>
          <!-- <td>{{ row.tags }}</td> -->
          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge badge-warning"
          >
            {{ item }}</span
          >
        </td>
        <td>
          <!-- 给删除按钮设置点击事件  -->
          <button class="btn btn-danger btn-sm" @click="delFn(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable.vue";
export default {
  data() {
    return {
      //设置一个空list接收
      list: [],
    };
  },
  //axios  请求数据
  created() {
    this.$axios({
      url: "/api/goods",
    })
      //将请求到的数据赋值给list
      .then((res) => {
        console.log(res);
        this.list = res.data.data;
      })
      //捕捉错误
      .catch((err) => {
        console.log(err);
      });
  },
  //注册MyTable组件
  components: {
    MyTable,
  },
  methods: {
    //删除事件
    delFn(id) {
      //将未被点击的项筛选出来赋给现在的list
      this.list = this.list.filter((item) => item.id !== id);
    },
    //回车键事件
    enterFn(row) {
      //如果输入框内容为空，提示弹框跳出，并return
      if (row.inputValue.trim() === "") {
        return alert("请输入内容");
      }
      //将输入框内容添加到tags中
      row.tags.push(row.inputValue);
      //清空输入框
      row.inputValue = "";
    },
  },
  //自定义指令----input自动获取焦点
  directives: {
    fff: {
      inserted(el) {
        el.focus();
      },
    },
  },
};
</script>

<style lang="less" scoped>
.my-goods-list {
  .badge {
    margin-right: 5px;
  }
}
</style>
